<template>
  <div class="parent-form-setting-wrap">
    <el-form
        size="small"
        @submit.prevent
        :model="formConfig"
        label-width="84px"
        class="parent-form-setting"
        label-position="left"
    >
      <el-collapse v-model="formActiveCollapseNames" class="parent-form-setting-collapse">
        <el-collapse-item name="1" title="全局设置">
          <template v-if="!!(formConfig?.parentInfo)">
            <el-form-item label="背景颜色">
              <div class="connect-wrap">
                <el-color-picker
                    size="small"
                    show-alpha
                    popper-class="linear-gradient-popper"
                    :predefine="predefineColors"
                    v-model="formConfig.parentInfo.backgroundColor"
                />
              </div>

            </el-form-item>
            <el-form-item label="背景图">
              <el-button type="primary" size="small" @click="handleSelect('formCarouselInfo')">
                背景图
              </el-button>
            </el-form-item>
          </template>
          <template v-if="!!(formConfig?.viewName)">
            <el-form-item label="路由名称">
              <el-input
                  type="text"
                  v-model="formConfig['viewName']"
              />
            </el-form-item>
          </template>
<!--        TODO 九龙坡区人民医院诊室屏模板增加此功能                -->
          <template v-if="!!(formConfig?.parentInfo)">
            <el-form-item label="内上边距">
              <el-input-number
                :min="0"
                size="small"
                v-model="formConfig.parentInfo.paddingTop"
              />
            </el-form-item>
            <el-form-item label="内下边距">
              <el-input-number
                :min="0"
                size="small"
                v-model="formConfig.parentInfo.paddingBottom"
              />
            </el-form-item>
            <el-form-item label="内左边距">
              <el-input-number
                :min="0"
                size="small"
                v-model="formConfig.parentInfo.paddingLeft"
              />
            </el-form-item>
            <el-form-item label="内右边距">
              <el-input-number
                :min="0"
                size="small"
                v-model="formConfig.parentInfo.paddingRight"
              />
            </el-form-item>
          </template>
        </el-collapse-item>
      </el-collapse>
    </el-form>
    <!--轮播图弹层-->
    <updatePicture
        @handleSure="handleSure"
        @handleCancel="handleCancel"
        :info="formCarouselInfo.info"
        :visible="formCarouselInfo.visible"
    />
  </div>
</template>

<script>
import updatePicture from "@c/public/layer/template/updatePicture";
import {deepClone, insertCustomCssToHead, insertGlobalFunctionsToHtml} from "@/utils/designer/util";
import * as types from "@c/public/form-designer/devType/datas-types";

export default {
  name: "parent-setting",

  mixins: [],

  components: {updatePicture},

  props: {
    designer: Object,
    formConfig: Object,
  },

  inject: ['getDesignerConfig'],

  data() {
    return {
      designerConfig: this.getDesignerConfig(),

      formActiveCollapseNames: ['1', '2'],

      formSizes: [
        {label: 'default', value: ''},
        {label: 'large', value: 'large'},
        {label: 'small', value: 'small'},
      ],

      showEditFormCssDialogFlag: false,

      formCssCode: '',

      cssClassList: [],

      showEditFunctionsDialogFlag: false,

      functionsCode: '',

      showFormEventDialogFlag: false,

      formEventHandlerCode: '',

      curEventName: '',

      eventParamsMap: {
        'onFormCreated': 'onFormCreated() {',
        'onFormMounted': 'onFormMounted() {',
        'onFormDataChange': 'onFormDataChange(fieldName, newValue, oldValue, formModel, subFormName, subFormRowIndex) {',
      },

      predefineColors: types['predefineColors'],

      // 轮播图
      formCarouselInfo: {
        info: '',
        visible: false,
      },
    }
  },

  created() {
    //导入表单JSON后需要重新加载自定义CSS样式！！！
    this.designer.handleEvent('form-json-imported', () => {
      this.formCssCode = this.formConfig.cssCode;
      insertCustomCssToHead(this.formCssCode);
      this.extractCssClass();
      this.designer.emitEvent('form-css-updated', deepClone(this.cssClassList));
    })
  },

  mounted() {
    /* SettingPanel和FormWidget为兄弟组件, 在FormWidget加载formConfig时，
       此处SettingPanel可能无法获取到formConfig.cssCode, 故加个延时函数！ */
    setTimeout(() => {
      this.formCssCode = this.formConfig.cssCode;
      insertCustomCssToHead(this.formCssCode);
      this.extractCssClass();
      this.designer.emitEvent('form-css-updated', deepClone(this.cssClassList));
    }, 1200)
  },

  methods: {
    showEventCollapse() {
      if (this.designerConfig['eventCollapse'] === undefined) {
        return true
      }
      return !!this.designerConfig['eventCollapse']
    },

    editFormCss() {
      this.formCssCode = this.designer.formConfig.cssCode;
      this.showEditFormCssDialogFlag = true;
    },

    saveFormCss() {
      this.extractCssClass()
      this.designer.formConfig.cssCode = this.formCssCode;
      insertCustomCssToHead(this.formCssCode);
      this.showEditFormCssDialogFlag = false;
      this.designer.emitEvent('form-css-updated', deepClone(this.cssClassList))
    },

    editGlobalFunctions() {
      this.functionsCode = this.designer.formConfig.functions;
      this.showEditFunctionsDialogFlag = true;
    },

    saveGlobalFunctions() {
      const codeHints = this.$refs.gfEditor?.getEditorAnnotations();
      let syntaxErrorFlag = false;
      if (!!codeHints && (codeHints.length > 0)) {
        codeHints.forEach((chItem) => {
          if (chItem.type === 'error') {
            syntaxErrorFlag = true;
          }
        })

        if (syntaxErrorFlag) {
          this.$message.error(this.i18nt('designer.setting.syntaxCheckWarning'));
          return
        }
      }

      this.designer.formConfig.functions = this.functionsCode
      insertGlobalFunctionsToHtml(this.functionsCode)
      this.showEditFunctionsDialogFlag = false
    },

    saveFormEventHandler() {
      const codeHints = this.$refs.ecEditor?.getEditorAnnotations();
      let syntaxErrorFlag = false
      if (!!codeHints && (codeHints.length > 0)) {
        codeHints.forEach((chItem) => {
          if (chItem.type === 'error') {
            syntaxErrorFlag = true
          }
        })

        if (syntaxErrorFlag) {
          this.$message.error(this.i18nt('designer.setting.syntaxCheckWarning'))
          return
        }
      }

      this.formConfig[this.curEventName] = this.formEventHandlerCode
      this.showFormEventDialogFlag = false
    },

    extractCssClass() {
      let regExp = /\..*{/g
      let result = this.formCssCode.match(regExp)
      let cssNameArray = []

      if (!!result && result.length > 0) {
        result.forEach((rItem) => {
          let classArray = rItem.split(',')  //切分逗号分割的多个class
          if (classArray.length > 0) {
            classArray.forEach((cItem) => {
              let caItem = cItem.trim()
              if (caItem.indexOf('.', 1) !== -1) {  //查找第二个.位置
                let newClass = caItem.substring(caItem.indexOf('.') + 1, caItem.indexOf('.', 1))  //仅截取第一、二个.号之间的class
                if (!!newClass) {
                  cssNameArray.push(newClass.trim())
                }
              } else if (caItem.indexOf(' ') !== -1) {  //查找第一个空格位置
                let newClass = caItem.substring(caItem.indexOf('.') + 1, caItem.indexOf(' '))  //仅截取第一、二个.号之间的class
                if (!!newClass) {
                  cssNameArray.push(newClass.trim())
                }
              } else {
                if (caItem.indexOf('{') !== -1) {  //查找第一个{位置
                  let newClass = caItem.substring(caItem.indexOf('.') + 1, caItem.indexOf('{'))
                  cssNameArray.push(newClass.trim())
                } else {
                  let newClass = caItem.substring(caItem.indexOf('.') + 1)
                  cssNameArray.push(newClass.trim())
                }
              }
            })
          }
        })
      }

      this.cssClassList.splice(0, this.cssClassList.length)  //清除数组必须用splice，length=0不会响应式更新！！
      this.cssClassList = Array.from(new Set(cssNameArray))  //数组去重
    },

    editFormEventHandler(eventName) {
      this.curEventName = eventName
      this.formEventHandlerCode = this.formConfig[eventName]
      this.showFormEventDialogFlag = true
    },

    // 选择文本内容&视频
    handleSelect(val) {
      let params = Object();
      switch (val) {
        case 'formCarouselInfo':
          // 查找资源库对应的资源
          Reflect.set(params, 'type', 'image');
          // 修改对应的字段
          Reflect.set(params, 'updataType', 'backgroundImage');
          // 是否支持多图片
          Reflect.set(params, 'multiple', false);
          Reflect.set(params, 'content', (this.formConfig.parentInfo['backgroundImageInfo']));
          Reflect.set((this.formCarouselInfo), 'visible', true);
          Reflect.set((this.formCarouselInfo), 'info', params);
          break
      }
    },

    // 更新就的数据
    handleSure(valInfo) {
      let {key, val} = valInfo;
      if (this.$lodash.isArray(val) && !!(val.length)) {
        Reflect.set((this.formConfig.parentInfo), key, val[0]['url']);
        Reflect.set((this.formConfig.parentInfo), 'backgroundImageInfo', val);
      } else {
        Reflect.set((this.formConfig.parentInfo), key, '');
        Reflect.set((this.formConfig.parentInfo), 'backgroundImageInfo', []);
      }
    },

    // 取消弹层
    handleCancel() {
      Reflect.set((this.formCarouselInfo), 'visible', false);
    },

  }
}
</script>

<style lang="scss" scoped>
.parent-form-setting-wrap {
  width: 100%;
  height: 100%;
  overflow-x: hidden;
  overflow-y: hidden;

  :deep(.el-collapse-item__wrap) {
    padding: 0 0.781vw;

    .el-collapse-item__content {
      padding-bottom: 16px !important;

      .el-form-item {
        &:last-child {
          margin-bottom: 0 !important;
        }

        .el-form-item__label {
          padding: 0 !important;
        }

        .connect-wrap {
          padding: 0 0.781vw;
        }
      }
    }
  }
}
</style>
